//
//  ViewController.m
//  CoreDataToStudentManagerSystem
//
//  Created by My Mac on 2017/6/14.
//  Copyright © 2017年 MyMac. All rights reserved.
//

#import "ViewController.h"
#import "Student+StudentInfo.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong) NSManagedObjectContext *managedObjectContext;
@property(nonatomic,strong) NSMutableArray *studentInfoData;
@property (weak, nonatomic) IBOutlet UILabel *noDataLabel;
@property(nonatomic,strong) UISearchController *searchController;
@property(nonatomic,strong) NSMutableArray *searchStudentInfoArr;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createSQLite];
    
    [self loadStudentInfoData];
    
    [self addStudentInfoRightBtn];
}

-(void) createSQLite
{
    /*
     一个NSManagedObjectModel对象描述了一种表结构-一个你的应用程序中实体类集合的描述.
     */
    NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    /*
     NSPersistentStoreCoordinator的实体对象维系数据库,以及在数据库和对象之间,操作句柄之间进行着通信.NSPersistentStoreCoordinator的实例对象通过协调的方式来将对象本地持久化以及将这个对象从本地中读取出来.
     */
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:managedObjectModel];
    NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //设置数据库的路径和文件名称和类型
    NSURL *url = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"Student.sqlite"]];
    // 添加持久化存储库，这里使用SQLite作为存储库
    NSError *error = nil;
    NSPersistentStore *perStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
    if (perStore == nil) {
        //如果数据库为空,直接抛异常
        [NSException raise:@"添加数据库错误" format:@"%@",error.localizedDescription];
    }
    // 初始化上下文，设置NSPersistentStoreCoordinator属性
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    _managedObjectContext.persistentStoreCoordinator = coordinator;
    //数据库会存在沙盒目录的Document文件夹下
    NSLog(@"Document File : %@",NSHomeDirectory());
}

-(void) loadStudentInfoData
{
    _tableView.tableFooterView = [UIView new];
    _tableView.tableHeaderView = [self setTableViewHeaderView];
    
    _studentInfoData = [NSMutableArray new];
    _searchStudentInfoArr = [NSMutableArray new];
    //创建一条查询请求
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
    /**
     * 通过条件查询
     * 例:设置条件为age=20的数据
     [request setPredicate:[NSPredicate predicateWithFormat:@"age == 20"]];
     */
    [fetchRequest setSortDescriptors:@[sortDescriptor]];
    //进行查询操作
    NSArray * stuInfoArr = [_managedObjectContext executeFetchRequest:fetchRequest error:nil];
    for (Student *stu in stuInfoArr) {
        [_studentInfoData addObject:stu];
    }
    NSLog(@"studentInfoData : %@",_studentInfoData);
}

-(UIView *)setTableViewHeaderView
{
    _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater = self;
    //搜索时背景是否显示
    _searchController.dimsBackgroundDuringPresentation = false;
    [_searchController.searchBar sizeToFit];
    _searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    _searchController.searchBar.placeholder = @"姓名/年龄";
    return _searchController.searchBar;
}

-(void) addStudentInfoRightBtn
{
    UIBarButtonItem *addStudentInfoBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addStudentInfoBtnClick:)];
    self.navigationItem.rightBarButtonItem = addStudentInfoBtn;
}

-(void) addStudentInfoBtnClick:(UIBarButtonItem *)rightBtn
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"添加学生信息" message:@"填写合理的学生姓名和年龄" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    //添加两个文本框
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor redColor];
        textField.placeholder = @"填写学生正确姓名";
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor blueColor];
        textField.placeholder = @"填写学生正确年龄";
    }];
    //确认按钮
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSString *name = alert.textFields[0].text;
        NSString *age = alert.textFields[1].text;
        NSLog(@"name:%@,age:%@",name,age);
        //将数据加入数据库
        NSManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_managedObjectContext];
        //可以像使用字典一样来给实体的属性赋值 KVC赋值
        [managedObject setValue:name forKey:@"name"];
        [managedObject setValue:age forKey:@"age"];
        
        NSError *error = nil;
        //每次改变实体后,都要保存上下文
        BOOL isSuccess = [_managedObjectContext save:&error];
        if (!isSuccess) {
            [NSException raise:@"访问数据库错误" format:@"%@", [error localizedDescription]];
        } else {
            NSLog(@"成功写入数据库!");
            [self loadStudentInfoData];
            [_tableView reloadData];
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_studentInfoData.count != 0) {
        _noDataLabel.hidden = YES;
    } else {
        _noDataLabel.hidden = NO;
    }
    if (_searchController.active) {
        return _searchStudentInfoArr.count;
    } else {
        return _studentInfoData.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"myCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    if (_searchController.active) {
        cell.textLabel.text = [_searchStudentInfoArr[indexPath.row] name];
        cell.detailTextLabel.text = [_searchStudentInfoArr[indexPath.row] age];
    } else {
        cell.textLabel.text = [_studentInfoData[indexPath.row] name];
        cell.detailTextLabel.text = [_studentInfoData[indexPath.row] age];
    }
    
    return cell;
}

-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //添加一个删除按钮
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"点击了删除");
        //1.更新数据
        [_managedObjectContext deleteObject:_studentInfoData[indexPath.row]];
        [_managedObjectContext save:nil];
        [self loadStudentInfoData];
        //2.更新视图
        [_tableView reloadData];
    }];
    //删除按钮颜色
    deleteAction.backgroundColor = [UIColor redColor];
    //添加修改按钮
    UITableViewRowAction *modifyAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"修改" handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改学生信息" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        //添加两个文本框
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.textColor = [UIColor redColor];
            textField.text = [_studentInfoData[indexPath.row] name];
        }];
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.textColor = [UIColor blueColor];
            textField.text = [_studentInfoData[indexPath.row] age];
        }];
        //确认按钮
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSString *name = alert.textFields[0].text;
            NSString *age = alert.textFields[1].text;
            NSLog(@"name:%@,age:%@",name,age);
            [_studentInfoData[indexPath.row] setValue:name forKey:@"name"];
            [_studentInfoData[indexPath.row] setValue:age forKey:@"age"];
            [_managedObjectContext save:nil];
            [self loadStudentInfoData];
            [_tableView reloadData];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }];
    //修改按钮颜色
    modifyAction.backgroundColor = [UIColor orangeColor];
    return @[deleteAction,modifyAction];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    [_searchStudentInfoArr removeAllObjects];
    NSMutableArray *tempMarr = [NSMutableArray new];
    for (Student *stu in _studentInfoData) {
        NSRange nameRange = [stu.name rangeOfString:searchController.searchBar.text options:NSCaseInsensitiveSearch];
        NSRange ageRange = [stu.age rangeOfString:searchController.searchBar.text options:NSCaseInsensitiveSearch];        if (nameRange.length > 0 || ageRange.length > 0) {
            [tempMarr addObject:stu];
        }
    }
    [_searchStudentInfoArr setArray:tempMarr];
    [_tableView reloadData];
}

@end
